var $ = window.$;
var jade = require('jade');
var Promise = require('bluebird');
var event = require('../../core/event');

/**
 *	通用io模块
 *  操纵file dialog，返回文件或目录路径，或者文本内容
 *  本身不持有数据，所以没有manager
 */

var _defer;
var _init = false;

var ret = {
	init: function(){
		if(_init){
			return;
		}
		this.dialog = {
			dir: $('#global_file_dir'),
			save: $('#global_file_save'),
			img: $('#global_file_img'),
			sound: $('#global_file_sound'),
			chart: $('#global_file_chart'),
			any: $('#global_any')
		};
		this.dialog.dir.change(this.onChange);
		this.dialog.save.change(this.onChange);
		this.dialog.img.change(this.onChange);
		this.dialog.sound.change(this.onChange);
		this.dialog.chart.change(this.onChange);
		this.dialog.any.change(this.onChange);

		_init = true;
	},

	onChange: function(e){
		if(_defer){
			var path = this.value;  //有多个文件时,这里以;隔开
			if(path){
				path = path.replace(/\\/g, '/');  //谜之nw内核
			}
			//先通知其他方
			if(path){
				event.trigger(event.events.global.dialog);
			}
			if(path.indexOf(';') > 0){
				_defer.resolve(path.split(';'));  //业务自己判断是数组还是string
			}else{
				_defer.resolve(path);
			}
		}
		this.value = null;
		_defer = null;
	},

	clearDefer: function(){
		if(_defer){
			_defer.resolve(null);
		}
	},

	getSavePath: function(conf){
		if(conf && conf.name){
			this.dialog.save.attr('nwsaveas', conf.name);
		}else{
			this.dialog.save.attr('nwsaveas', '');
		}
		var defer = Promise.defer();
		this.clearDefer();
		_defer = defer;
		this.dialog.save.trigger('click');
		return defer.promise;
	},

	getImgPath: function (conf) {
		var defer = Promise.defer();
		this.clearDefer();
		_defer = defer;
		this.dialog.img.trigger('click');
		return defer.promise;
	},

	getChartPath: function(conf){
		var defer = Promise.defer();
		this.clearDefer();
		_defer = defer;
		this.dialog.chart.trigger('click');
		return defer.promise;
	},

	getSoundPath: function(conf){
		var defer = Promise.defer();
		this.clearDefer();
		_defer = defer;
		this.dialog.sound.trigger('click');
		return defer.promise;
	},

	getDir: function(conf){
		var defer = Promise.defer();
		this.clearDefer();
		_defer = defer;
		this.dialog.dir.trigger('click');
		return defer.promise;
	},

	getAny: function(conf){
		var defer = Promise.defer();
		this.clearDefer();
		_defer = defer;
		this.dialog.any.trigger('click');
		return defer.promise;
	}
};

module.exports = ret;